<template>
  <nut-wrapper>
    <view class="security-container">
      <!-- 修改密码 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-lock"></i>
          <text>账号密码</text>
        </view>
        <nut-cell-group>
          <nut-cell
            title="修改密码"
            is-link
            @click="showPasswordDialog"
          ></nut-cell>
        </nut-cell-group>
      </view>

      <!-- 手机号 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-phone"></i>
          <text>手机号</text>
        </view>
        <nut-cell-group>
          <nut-cell
            :title="userInfo.phone || '未绑定'"
            :label="userInfo.phone ? '已绑定' : '未绑定手机号'"
            is-link
            @click="showPhoneDialog"
          ></nut-cell>
        </nut-cell-group>
      </view>

      <!-- 邮箱 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-email"></i>
          <text>邮箱</text>
        </view>
        <nut-cell-group>
          <nut-cell
            :title="userInfo.email || '未绑定'"
            :label="userInfo.email ? '已绑定' : '未绑定邮箱'"
            is-link
            @click="showEmailDialog"
          ></nut-cell>
        </nut-cell-group>
      </view>

      <!-- 账号注销 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-warning"></i>
          <text>账号注销</text>
        </view>
        <nut-cell-group>
          <nut-cell
            title="注销账号"
            is-link
            @click="showDeleteAccountDialog"
          ></nut-cell>
        </nut-cell-group>
      </view>

      <!-- 修改密码弹窗 -->
      <nut-dialog
        title="修改密码"
        v-model:visible="passwordDialogVisible"
        @ok="updatePassword"
        @cancel="passwordDialogVisible = false"
      >
        <nut-form>
          <nut-form-item label="原密码">
            <nut-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
            />
          </nut-form-item>
          <nut-form-item label="新密码">
            <nut-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
            />
          </nut-form-item>
          <nut-form-item label="确认密码">
            <nut-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
            />
          </nut-form-item>
        </nut-form>
      </nut-dialog>

      <!-- 绑定手机号弹窗 -->
      <nut-dialog
        title="绑定手机号"
        v-model:visible="phoneDialogVisible"
        @ok="updatePhone"
        @cancel="phoneDialogVisible = false"
      >
        <nut-form>
          <nut-form-item label="手机号">
            <nut-input
              v-model="phoneForm.phone"
              type="tel"
              placeholder="请输入手机号"
            />
          </nut-form-item>
          <nut-form-item label="验证码">
            <nut-input
              v-model="phoneForm.code"
              type="number"
              placeholder="请输入验证码"
            >
              <template #right>
                <nut-button
                  size="mini"
                  type="primary"
                  :disabled="countdown > 0"
                  @click="sendSmsCode"
                >
                  {{ countdown > 0 ? `${countdown}s后重试` : "获取验证码" }}
                </nut-button>
              </template>
            </nut-input>
          </nut-form-item>
        </nut-form>
      </nut-dialog>

      <!-- 绑定邮箱弹窗 -->
      <nut-dialog
        title="绑定邮箱"
        v-model:visible="emailDialogVisible"
        @ok="updateEmail"
        @cancel="emailDialogVisible = false"
      >
        <nut-form>
          <nut-form-item label="邮箱">
            <nut-input
              v-model="emailForm.email"
              type="email"
              placeholder="请输入邮箱"
            />
          </nut-form-item>
          <nut-form-item label="验证码">
            <nut-input
              v-model="emailForm.code"
              type="number"
              placeholder="请输入验证码"
            >
              <template #right>
                <nut-button
                  size="mini"
                  type="primary"
                  :disabled="countdown > 0"
                  @click="sendEmailCode"
                >
                  {{ countdown > 0 ? `${countdown}s后重试` : "获取验证码" }}
                </nut-button>
              </template>
            </nut-input>
          </nut-form-item>
        </nut-form>
      </nut-dialog>

      <!-- 注销账号弹窗 -->
      <nut-dialog
        title="注销账号"
        v-model:visible="deleteAccountDialogVisible"
        @ok="deleteAccount"
        @cancel="deleteAccountDialogVisible = false"
      >
        <view class="delete-account-content">
          <text>注销账号后，您的所有数据将被永久删除，且无法恢复。</text>
          <text>请确认是否继续？</text>
        </view>
      </nut-dialog>
    </view>
  </nut-wrapper>
</template>

<script>
import Taro from "@tarojs/taro";
import { useUserStore } from "@/stores/userStore";
import {
  trackPageView,
  trackClick,
  trackFormSubmit,
  trackUserInfo,
} from "@/services/tracking";
export default {
  name: "Security",
  data() {
    return {
      passwordDialogVisible: false,
      phoneDialogVisible: false,
      emailDialogVisible: false,
      deleteAccountDialogVisible: false,
      countdown: 0,
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      phoneForm: {
        phone: "",
        code: "",
      },
      emailForm: {
        email: "",
        code: "",
      },
    };
  },
  computed: {
    userInfo() {
      return this.userStore.getUserInfo;
    },
  },
  setup() {
    const userStore = useUserStore();
    return { userStore };
  },
  methods: {
    showPasswordDialog() {
      trackClick("password_dialog", "修改密码");
      this.passwordForm = {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      };
      this.passwordDialogVisible = true;
    },
    showPhoneDialog() {
      this.phoneForm = {
        phone: this.userInfo.phone || "",
        code: "",
      };
      this.phoneDialogVisible = true;
    },
    showEmailDialog() {
      this.emailForm = {
        email: this.userInfo.email || "",
        code: "",
      };
      this.emailDialogVisible = true;
    },
    showDeleteAccountDialog() {
      this.deleteAccountDialogVisible = true;
    },
    async updatePassword() {
      if (!this.validatePassword()) return;

      try {
        // 这里添加实际的修改密码逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        Taro.showToast({
          title: "密码修改成功",
          icon: "success",
        });
        this.passwordDialogVisible = false;
      } catch (error) {
        Taro.showToast({
          title: "密码修改失败",
          icon: "error",
        });
      }
    },
    async updatePhone() {
      if (!this.validatePhone()) return;

      try {
        // 这里添加实际的绑定手机号逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.userStore.updateUserField("phone", this.phoneForm.phone);
        Taro.showToast({
          title: "手机号绑定成功",
          icon: "success",
        });
        this.phoneDialogVisible = false;
      } catch (error) {
        Taro.showToast({
          title: "手机号绑定失败",
          icon: "error",
        });
      }
    },
    async updateEmail() {
      if (!this.validateEmail()) return;

      try {
        // 这里添加实际的绑定邮箱逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.userStore.updateUserField("email", this.emailForm.email);
        Taro.showToast({
          title: "邮箱绑定成功",
          icon: "success",
        });
        this.emailDialogVisible = false;
      } catch (error) {
        Taro.showToast({
          title: "邮箱绑定失败",
          icon: "error",
        });
      }
    },
    async deleteAccount() {
      try {
        // 这里添加实际的注销账号逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.userStore.clearUserInfo();
        Taro.showToast({
          title: "账号已注销",
          icon: "success",
        });
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/index/index",
          });
        }, 1500);
      } catch (error) {
        Taro.showToast({
          title: "注销失败",
          icon: "error",
        });
      }
    },
    validatePassword() {
      if (!this.passwordForm.oldPassword) {
        Taro.showToast({
          title: "请输入原密码",
          icon: "none",
        });
        return false;
      }
      if (!this.passwordForm.newPassword) {
        Taro.showToast({
          title: "请输入新密码",
          icon: "none",
        });
        return false;
      }
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        Taro.showToast({
          title: "两次输入的密码不一致",
          icon: "none",
        });
        return false;
      }
      return true;
    },
    validatePhone() {
      if (!this.phoneForm.phone) {
        Taro.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
        Taro.showToast({
          title: "请输入正确的手机号",
          icon: "none",
        });
        return false;
      }
      if (!this.phoneForm.code) {
        Taro.showToast({
          title: "请输入验证码",
          icon: "none",
        });
        return false;
      }
      return true;
    },
    validateEmail() {
      if (!this.emailForm.email) {
        Taro.showToast({
          title: "请输入邮箱",
          icon: "none",
        });
        return false;
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.emailForm.email)) {
        Taro.showToast({
          title: "请输入正确的邮箱",
          icon: "none",
        });
        return false;
      }
      if (!this.emailForm.code) {
        Taro.showToast({
          title: "请输入验证码",
          icon: "none",
        });
        return false;
      }
      return true;
    },
    async sendSmsCode() {
      if (!this.phoneForm.phone) {
        Taro.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
        Taro.showToast({
          title: "请输入正确的手机号",
          icon: "none",
        });
        return;
      }

      try {
        // 这里添加实际的发送验证码逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.startCountdown();
        Taro.showToast({
          title: "验证码已发送",
          icon: "success",
        });
      } catch (error) {
        Taro.showToast({
          title: "验证码发送失败",
          icon: "error",
        });
      }
    },
    async sendEmailCode() {
      if (!this.emailForm.email) {
        Taro.showToast({
          title: "请输入邮箱",
          icon: "none",
        });
        return;
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.emailForm.email)) {
        Taro.showToast({
          title: "请输入正确的邮箱",
          icon: "none",
        });
        return;
      }

      try {
        // 这里添加实际的发送验证码逻辑
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.startCountdown();
        Taro.showToast({
          title: "验证码已发送",
          icon: "success",
        });
      } catch (error) {
        Taro.showToast({
          title: "验证码发送失败",
          icon: "error",
        });
      }
    },
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
  },
};
</script>

<style lang="scss">
.security-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 40rpx;

  .section {
    margin: 30rpx;
    padding: 30rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      font-size: $font-size-2;
      font-weight: bold;
      color: $text-color;

      i {
        margin-right: 10rpx;
        color: $primary-color;
        font-size: 40rpx;
      }
    }
  }

  .nut-form-item {
    margin-bottom: 30rpx;

    .nut-form-item__label {
      font-size: $font-size-1;
      color: $text-color;
      width: 160rpx;
    }
  }

  .delete-account-content {
    padding: 20rpx;
    text-align: center;
    color: $primary-color;
    font-size: $font-size-1;

    text {
      display: block;
      margin-bottom: 10rpx;
    }
  }

  // 深色模式样式
  [data-theme="dark"] {
    .security-container {
      background-color: #000;
    }

    .section {
      background-color: #000;
      box-shadow: none;
    }
  }
}
</style>
